package com.peng.leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Connect
 * 116. 填充每个节点的下一个右侧节点指针
 *
 * @author: lupeng6
 * @create: 2021/1/28 18:08
 */
public class Connect {

    public static void main(String[] args) {

    }

    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            for (int i = 0; i < queue.size(); i++) {
                Node curr = queue.poll();
                if (i == queue.size() - 1) {
                    curr.next = null;
                } else {
                    curr.next = queue.peek();
                }
                if (curr.left != null) {
                    queue.offer(curr.left);
                }
                if (curr.right != null) {
                    queue.offer(curr.right);
                }
            }
        }
        return root;
    }
}


class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};